﻿using System;
using System.Text.Json;

namespace NiuX.Json;

/// <summary>
/// Json 扩展方法
/// </summary>
public static class JsonExtensions
{
    public static JsonSerializerOptions? DefaultJsonSerializerOptions { get; set; }

    /// <summary>
    /// 从 Json 反序列化
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="str"></param>
    /// <returns></returns>
    //public static T? FromJson<T>(this string str) => JsonConvert.DeserializeObject<T>(str);
    public static T? FromJson<T>(this string str) => System.Text.Json.JsonSerializer.Deserialize<T>(str);

    ///// <summary>
    ///// 把对象序列化成 Json 字符串格式
    ///// </summary>
    ///// <param name="obj">Json 对象</param>
    ///// <param name="isCamelCase">是否小写名称</param>
    ///// <param name="indented"></param>
    ///// <returns>Json 字符串</returns>
    //public static string ToJson(this object obj, bool isCamelCase, bool indented = false) =>
    //    isCamelCase switch
    //    {
    //        true when indented => obj.ToJson(JsonSerializerSettingsInstance.CamelCaseAndIndented),
    //        true => obj.ToJson(JsonSerializerSettingsInstance.CamelCase),
    //        _ => indented switch
    //        {
    //            true => obj.ToJson(JsonSerializerSettingsInstance.FormattingIndented),
    //            _ => obj.ToJson()
    //        }
    //    };
    /// <summary>
    /// 从 Json 反序列化
    /// </summary>
    /// <returns></returns>
    //public static object? FromJson(this string str, Type type) => JsonConvert.DeserializeObject(str, type);
    public static object? FromJson(this string str, Type type) => System.Text.Json.JsonSerializer.Deserialize(str, type);

    /// <summary>
    /// 从 Json 反序列化
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <returns></returns>
    //public static T? FromJson<T>(this string str, Type type) => (T?)JsonConvert.DeserializeObject(str, type);
    public static T? FromJson<T>(this string str, Type type) => (T?)System.Text.Json.JsonSerializer.Deserialize(str, type);

    /// <summary>
    /// 序列化成 Json
    /// </summary>
    /// <param name="obj"></param>
    /// <returns></returns>
    public static string ToJson(this object obj)
    {
        return System.Text.Json.JsonSerializer.Serialize(obj, DefaultJsonSerializerOptions);

        //return JsonConvert.SerializeObject(obj);
    }

    ///// <summary>
    ///// 序列化成 Json
    ///// </summary>
    ///// <returns></returns>
    //public static string ToJson(this object obj, JsonSerializerSettings settings)
    //{
    //    return JsonConvert.SerializeObject(obj, settings);
    //}

    /// <summary>
    /// 序列化成 Json
    /// </summary>
    /// <returns></returns>
    public static string ToJson(this object obj, JsonSerializerOptions options)
    {
        return System.Text.Json.JsonSerializer.Serialize(obj, options);
    }
}